package com.rk.kbk.controller;

import com.alibaba.fastjson.JSONObject;
import com.rk.kbk.common.FailException;
import com.rk.kbk.common.JsonResp;
import com.rk.kbk.common.PubLib;
import com.rk.kbk.dao.AddressDao;
import com.rk.kbk.dao.GoodsDao;
import com.rk.kbk.dao.GoodsUnitDao;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.Address;
import com.rk.kbk.model.Goods;
import com.rk.kbk.model.GoodsUnit;
import org.apache.log4j.Logger;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @GoodsUnitController
 * @商品价格Controller
 * @version : Ver 1.0
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/goodsUnit")
public class GoodsUnitController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private GoodsUnitDao goodsUnitDao;
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private GoodsDao goodsDao;
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * @添加/修改商品价格
     * @param goodsUnit
     * @param marketPrice 商品价格
     * @param id goodsId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateGoodsUnit",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateGoodsUnit(@RequestBody GoodsUnit goodsUnit,String marketPrice,String unitPrice,Long id){
        log.debug("添加/修改商品价格");
        if(id!=null){// 说明修改
            Goods goodsOld=goodsDao.findOne(id);
            List <GoodsUnit> list =goodsUnitDao.findByGoods(goodsOld);
            for(GoodsUnit g :list){
                g.setStatus(2);
            }
            goodsOld.setTitle(goodsUnit.getGoods().getTitle());
            goodsOld.setGoodsType(goodsUnit.getGoods().getGoodsType());
            goodsOld.setGoodsUrl(goodsUnit.getGoods().getGoodsUrl());
            goodsOld.setGoodsDetail(goodsUnit.getGoods().getGoodsDetail());
            goodsOld.setStatus(goodsUnit.getStatus());
            goodsDao.save(goodsOld);
            //遍历价格和规格
            String unitStandard = goodsUnit.getUnitStandard();
            String [] standardArray = unitStandard.split(",");
            String [] priceArray = marketPrice.split(",");
            String [] priceArraytwo = unitPrice.split(",");
            if(standardArray.length==priceArray.length){
                for(int i=0;i<standardArray.length;i++){
                    GoodsUnit g = new GoodsUnit();
                    g.setStatus(goodsUnit.getStatus());
                    g.setUnitStandard(standardArray[i]);
                    g.setMarketPrice(Double.parseDouble(priceArray[i]));
                    g.setUnitPrice(Double.parseDouble(priceArraytwo[i]));
                    g.setGoods(goodsOld);
                    goodsUnitDao.save(g);
                }
            }else {
                throw new FailException("规格和价格不一致！");
            }
        }else {//添加
            Goods goods = new Goods();
            goods.setTitle(goodsUnit.getGoods().getTitle());
            goods.setGoodsType(goodsUnit.getGoods().getGoodsType());
            goods.setGoodsUrl(goodsUnit.getGoods().getGoodsUrl());
            goods.setGoodsDetail(goodsUnit.getGoods().getGoodsDetail());
            goods.setStatus(1);
            goodsDao.save(goods);
            //遍历价格和规格
            String unitStandard = goodsUnit.getUnitStandard();
            String [] standardArray = unitStandard.split(",");
            String [] priceArray = marketPrice.split(",");
            String [] priceArraytwo = unitPrice.split(",");
            if(standardArray.length==priceArray.length){
                for(int i=0;i<standardArray.length;i++){
                    GoodsUnit g = new GoodsUnit();
                    g.setStatus(goodsUnit.getStatus());
                    g.setUnitStandard(standardArray[i]);
                    g.setMarketPrice(Double.parseDouble(priceArray[i]));
                    g.setUnitPrice(Double.parseDouble(priceArraytwo[i]));
                    g.setGoods(goods);
                    goodsUnitDao.save(g);
                }
            }else {
                throw new FailException("规格和价格不一致！");
            }

        }
          return JsonResp.ok();
    }

    /**
     * @批量添加/修改商品价格
     * @param goodsUnits
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSomeGoodsUnit",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomeGoodsUnit(@RequestBody List<GoodsUnit> goodsUnits){
        log.debug("批量添加/修改商品价格");
        goodsUnitDao.save(goodsUnits);
        return JsonResp.ok();
    }

    /**
     * @获取商品价格详情-ByGoodsUnitId
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/goodsUnitDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findGoodsUnitDetailsByGoodsUnitId(Long id) {
        log.debug("获取商品价格详情-ByGoodsUnitId");
        GoodsUnit goodsUnit=goodsUnitDao.findOne(id);
        Goods goods=goodsUnit.getGoods();
        Address address=goods.getAddress();
        Map map=new HashMap();
        map.put("title",goods.getTitle());
        map.put("goodsType",goods.getGoodsType());
        map.put("marketPrice",goodsUnit.getMarketPrice());
        map.put("unitStandard",goodsUnit.getUnitStandard());
        map.put("goodsUrl", goods.getGoodsUrl());
        map.put("goodsDetail",goods.getGoodsDetail());
        return JsonResp.ok(map);
    }

    /**
     * @分页查询商品价格(jpa方式)
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/getGoodsList",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getGoodsList(@RequestBody JSONObject jsonObject) {
        log.debug("分页查询商品价格(jpa方式)");
        Integer pageNum = Integer.parseInt(String.valueOf(jsonObject.get("pageNum")))-1;
        Integer pageSize = Integer.parseInt(String.valueOf(jsonObject.get("pageSize")));
        Integer type=Integer.parseInt(String.valueOf(jsonObject.get("type")));
         String sql="FROM goods WHERE goods_type="+ type +" And status =1 ORDER BY gmt_datetime DESC";
        Query query = entityManager.createNativeQuery("SELECT * "+sql);
        Query querySize = entityManager.createNativeQuery("SELECT COUNT(1) "+sql);
        BigInteger count_number = (BigInteger) querySize.getSingleResult();
        long total = count_number.longValue();
        //分页
        if ((pageNum-1) >= 0) {
            query.setFirstResult((pageNum-1) * pageSize);
        }
        if (pageSize > 0) {
            query.setMaxResults(pageSize);
        }
        entityManager.close();
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map> mapList = new ArrayList<>();
        query.getResultList().forEach(n -> mapList.add(PubLib.copyObject(PubLib.convert(n), Map.class)));
        return JsonResp.ok(new PageDto(pageNum, pageSize, mapList, total));

    }

    /**
     * @删除商品-one(永久)
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteGoodsOne",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteGoodsOne(Long id) {
        log.debug("删除商品-one(永久)");
        Goods goods = goodsDao.findOne(id);
        goods.setStatus(0);
        goodsDao.save(goods);
        List<GoodsUnit> list=goodsUnitDao.findByGoods(goods);
        for(GoodsUnit g:list){
            g.setStatus(2);
        }
        goodsUnitDao.save(list);
        return JsonResp.ok();
    }

    /**
     * @批量删除商品价格(永久)
     * @param goodsUnits
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSomeGoodsUnit",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSomeGoodsUnit(@RequestBody List<GoodsUnit> goodsUnits) {
        log.debug("批量删除商品价格(永久)");
        goodsUnitDao.delete(goodsUnits);
        return JsonResp.ok();
    }





}
